import request from '@/utils/request'
import { LOGIN, LOGOUT } from '../constants'
import { setToken, removeToken } from '@/utils'

// 登录
export const loginAc = (payload) => ({ type: LOGIN, payload })
export const login = (payload) => {
  return async (dispatch) => {
    const res = await request({
      method: 'post',
      url: '/authorizations',
      data: payload,
    })
    const token = res.data.data.token
    setToken(token)
    dispatch(loginAc(token))
  }
}

// 退出
export const logoutAc = () => ({ type: LOGOUT })
// 下面写法也 OK
/* export const logout = () => {
  removeToken()
  return logoutAc()
} */
// 更建议下面写法
export const logout = () => {
  return (dispatch) => {
    removeToken()
    dispatch(logoutAc())
  }
}
